import 'dart:ui' as ui;
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_image_gallery_saver/flutter_image_gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'package:qr_flutter/qr_flutter.dart';

import '../common/utils.dart';
import '../controllers/video_related_controller.dart';

class VideoShareDialog extends StatelessWidget {
  final GlobalKey _key = GlobalKey();

  VideoShareDialog({super.key});

  Future<void> _captureAndSaveToGallery() async {
    try {
      RenderRepaintBoundary boundary = _key.currentContext?.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();

      // Save to gallery
      await FlutterImageGallerySaver.saveImage(
        pngBytes,
      );

      Fluttertoast.showToast(msg: '已保存到相册～');
    } catch (e) {
      Fluttertoast.showToast(msg: '保存失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final vc = Get.find<VideoRelatedController>();
    return Dialog.fullscreen(
      backgroundColor: Colors.white,
      child: Container(
        padding: EdgeInsets.only(left: 20, top: 100, right: 20),
        child: Column(
          children: [
            RepaintBoundary(
              key: _key,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.grey.shade200),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CachedNetworkImage(
                      width: double.infinity,
                      height: 200,
                      fit: BoxFit.cover,
                      imageUrl: vc.videoInfo.value?.video.cover.url ?? '',
                      placeholder: (context, url) => Image.asset(
                        "assets/images/placeholder.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 10, right: 10),
                      child: Text(
                        vc.videoInfo.value?.video.title ?? '',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 10, right: 10),
                      child: Text(
                        vc.videoInfo.value?.video.descriptionEditor ?? '',
                        style: TextStyle(fontSize: 12, color: Colors.black87),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 10),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            "#${isEmpty(vc.videoInfo.value?.video.titlePgc ?? '') ? (vc.videoInfo.value?.category?.name ?? '') : (vc.videoInfo.value?.video.titlePgc ?? '')}",
                            style: TextStyle(color: Colors.black45, fontSize: 12),
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 5),
                            child: Icon(
                              Icons.play_circle_outlined,
                              color: Colors.black45,
                              size: 15,
                            ),
                          ),
                          Text(
                            formatSeconds2(vc.videoInfo.value?.video.duration.value ?? 0),
                            style: TextStyle(color: Colors.black45, fontSize: 12, fontFamily: 'OpenSans'),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                    Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Row(
                        children: [
                          Image.asset(
                            "assets/images/icon_poster_logo.png",
                            width: 100,
                            fit: BoxFit.cover,
                          ),
                          Spacer(),
                          Image.asset(
                            "assets/images/icon_poster_scan_tips.png",
                            width: 50,
                            fit: BoxFit.cover,
                          ),
                          QrImageView(
                            data: vc.videoInfo.value?.link ?? '',
                            size: 75,
                            gapless: false,
                            embeddedImage: AssetImage('assets/images/logo_eyepeziter.png'),
                            embeddedImageStyle: QrEmbeddedImageStyle(
                              size: Size(14, 14),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                  ],
                ),
              ),
            ),
            Spacer(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildShareIcon(Icons.facebook, 'Facebook', () {}),
                _buildShareIcon(Icons.wechat, '微信', () {}),
                _buildShareIcon(Icons.apple, 'Apple', () {}),
                _buildShareIcon(Icons.download, '保存到本地', _captureAndSaveToGallery),
              ],
            ),
            Divider(color: Colors.grey[100]),
            TextButton(
              onPressed: () {
                Get.back();
              },
              child: Text(
                "取消",
                style: TextStyle(fontSize: 15),
              ),
            ),
            SizedBox(height: 30),
          ],
        ),
      ),
    );
  }

  Widget _buildShareIcon(IconData icon, String label, VoidCallback onTap) {
    return Column(
      children: [
        IconButton(
          icon: Icon(icon, size: 30),
          onPressed: onTap,
        ),
        Text(label, style: TextStyle(fontSize: 12)),
      ],
    );
  }
}
